<?php
/**
 * 公共类
 */
class Common{
    # code
    public $treeList;
    /**
     * 不可逆加密
     * @author Toby.tu 2016-08-30
     */
    public function pwd($code=''){
        if(empty($code)){
            return '';
        }
        $key = config_item('common_pwd_key').'_dslr_pwd_encode';
        $pwd = sha1($key).sha1($code);
        return md5(sha1($key).sha1($pwd));
    }
	/**
	 * 可逆加密
	 * @author Tujt 2017-1-4
	 */
	public function encode($key='',$code='') {
        if(empty($key) || empty($code)) return '';
        $CI = & get_instance();
        $CI->load->library('encryption');
        $CI->encryption->initialize(
            array(
                'cipher' => 'aes-256',
                'mode' => 'ctr',
                'key' => $key.config_item('encryption_pwd_key')
            )
        );
        return $CI->encryption->encrypt($code);
	}
	/**
	 * 可逆解密
	 * @author Tujt 2017-1-4
	 */
	public function decode($key='',$code='') {
        if(empty($key) || empty($code)) return '';
        $CI = & get_instance();
        $CI->load->library('encryption');
        $CI->encryption->initialize(
            array(
                'cipher' => 'aes-256',
                'mode' => 'ctr',
                'key' => $key.config_item('encryption_pwd_key')
            )
        );
        return $CI->encryption->decrypt($code);
	}
    /**
     * 获取菜单
     * @author Toby.tu 2016-09-08
     */
    public function getMenuInfo(){
        $CI = & get_instance();
        $CI->vendor('logic/PermissionLogic','permis');
        $menus = $CI->permis->getMenuInfo();
        if(empty($menus)) return '';
        $iconarr = array('fa fa-dashboard','fa fa-cubes','fa fa-table','fa fa-money','fa fa-gift','fa fa-home','fa fa-group','fa fa-key','fa fa-cogs');
        $idx = 0;$maxicon = count($iconarr);
        $menuinfo = array();
        $router = $CI->permis->getRouter();
        if('store' == $router['method']){
            $router['method'] = 'create';
        }else if('update' == $router['method']){
            $router['method'] = 'edit';
        }
        $url = $router['group'].'/'.$router['controller'].'/'.$router['method'];
        $f = false;
        $CI->load->model('Menu_model','menu_model');
        $menulist = $CI->menu_model->getAll();
        foreach ($menulist as $menuarr){
            //菜单不显示的情况，应该默认选中菜单的index跟菜单
            if(strtolower($menuarr['url']) == $url && 2 != $menuarr['type']){
                $f = true;break;
            }
        }
        if(!$f){
            $url = $router['group'].'/'.$router['controller'].'/index';
        }
        $active = array();
        $currenturl = $CI->permis->router->uri->uri_string;//当前页
        foreach ($menus as $menu) {
            $menuarr = array();
            $menuarr['id'] = $menu['info']['id'];
            $menuarr['title'] = $menu['info']['name'];
            if(!isset($iconarr[$idx])){
                $idx = 0;
            }
            $menuarr['icon'] = $iconarr[$idx];
            $menuarr['url'] = '';
            $idx ++;
            if(!isset($menu['list']) && empty($menu['info']['url'])){
                continue;
            }
            foreach ($menu['list'] as $list) {
                $menulist = array();
                $menulist['id'] = $list['info']['id'];
                $menulist['title'] = $list['info']['name'];
                $menulist['url'] = base_url().'index.php/'.$list['info']['url'];
                if($url == strtolower($list['info']['url'])){
                    $menuurlarr = explode('/',$menulist['url']);
                    if('index' != end($menuurlarr))
                        $menulist['url'] = base_url().'index.php/'.$currenturl;
                    $active[] = $menu['info']['id'];
                    $active[] = $list['info']['id'];
                }
                $menuarr['list'][] = $menulist;
            }
            $menuinfo[] = $menuarr;
        }
        if(!empty($menuinfo))
            return json_encode(array('active'=>$active,'dataList'=>$menuinfo));
        return '';
    }
    /**
     * 如果文件夹不存在，则递归创建文件夹
     * @param String $path 目录
     * @author Tujt 2013-07-08
     */
    public function createdir($path){
        if (!file_exists($path)){
            $this->createdir(dirname($path));//递归创建文件夹
            mkdir($path, 0777);
        }
    }
    /**
     * 如果文件不存在，则创建文件
     * @param String $path 目录
     * @author Tujt 2013-07-08
     */
    public function createfile($route){
        if (!file_exists($route)){
            touch($route);
        }
    }
    /**
     * 多级菜单排序
     * @author Toby.tu 2017-03-06
     */
    public function sortLevelArray(&$data,$pid = 0,$count = 0){
        foreach ($data as $key => $value){
            if($value['parent_id'] == $pid){
                $value['count'] = $count;
                $this->treeList[] = $value;
                unset($data[$key]);
                $this->sortLevelArray($data,$value['id'],$value['parent_id']+1);
            }
        }
        return $this->treeList;
    }
    /**
     * 缓存统一方法
     * @author Toby.tu 2016-12-26
     */
    public function Cache($key='',$data='$$_cache_&&_data_##',$time=0){
        if(empty($key)){
            return array();
        }
        $key .= config_item('cache_key');
        $CI = &get_instance();
        static $cache_redis_object;//增加静态变量，防止同一个进程多次链接redis
        if(!$cache_redis_object){
            $CI->load->driver('cache');
            $cache_redis_object = $CI->cache;
            // //初始化redis类
            // include_once APPPATH.'libraries/predis/Autoloader.php';
            // \Predis\Autoloader::register();
            // $conf = array(
            //     'scheme' => 'tcp',
            //     'host'   => config_item('redis_config')['REDIS_HOST'],
            //     'port'   => 6379,
            // );
            // $cache_redis_object = new \Predis\Client($conf);
        }
        $redis = $cache_redis_object;
        $cache_key = 'woaap_crm_'.$key;
        if('$$_cache_&&_data_##' != $data){//存入缓存
            if(!empty($data)) $val = serialize($data);
            else $val = '';
            // $redis->set($cache_key,$val);
            // $redis->expire($cache_key,$time);
            $CI->cache->file->save($cache_key,$val,$time);//一天
        }else{//取出缓存
            $data = $CI->cache->file->get($cache_key);
            // $data = $redis->get($cache_key);
            if(!empty($data)) $data = unserialize($data);
        }
        return $data;
    }
    /**
     * 将字符串转换为指定格式
     * @author Tujt 2014-02-10
     */
    public static function setDataToCode($string, $code = 'UTF-8') {
        $arr = array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG-5');
        $encode = mb_detect_encoding($string, $arr);
        if (strtolower($encode) != strtolower($code)) {
            $string = iconv($encode, $code, $string);
        }
        return $string;
    }
    /**
     * 生成签名
     * @author Toby.tu 2017-02-08
     */
    public function getSign($param=[]){
        if(empty($param)) return false;
        sort($param);
        return sha1(json_encode($param));
    }
}
?>
